import csv
import os
from math import nan

import chardet
import numpy as np

import matplotlib.pyplot as plt
import pandas as pd

# 设置字体以支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体
plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题


def show(data):
    # 提取数据
    keys = list(data.keys())
    up_rate = [d['up_rate'] for d in data.values() if 'up_rate' in d]
    down_rate = [d['down_rate'] for d in data.values() if 'down_rate' in d]
    all_rate = [d['all_rate'] for d in data.values() if 'all_rate' in d]

    # 创建图形和坐标轴
    fig, ax = plt.subplots()
    # 绘制柱状图
    bar_width = 0.35
    indices = np.arange(len(keys))

    # 第一组柱状图
    rects1 = ax.bar(indices, up_rate, bar_width, label='上游门架匹配率')
    # 第二组柱状图
    rects2 = ax.bar(indices + bar_width, down_rate, bar_width, label='下游门架匹配率')
    # 第三组柱状图
    rects3 = ax.bar(indices + bar_width * 2, all_rate, bar_width, label='总体匹配率')

    # # 设置 x 轴的刻度和标签，每隔12个显示一次
    # ticks = indices[::12]  # 每隔12个索引选取一个
    # tick_labels = keys[::12]  # 对应的标签也每隔12个选取一个

    # 添加标签和标题
    ax.set_xlabel('事件简称')
    ax.set_ylabel('匹配率（百分比）')
    ax.set_title('事件上下游门架匹配率')
    ax.set_xticks(indices + bar_width*1)
    ax.set_xticklabels(keys)
    ax.legend()

    # # 叠加折线图
    # diff = [d['flow_diff'] for d in data.values() if 'flow_diff' in d]
    # ax2 = ax.twinx()  # 创建第二个y轴
    # ax2.plot(indices, diff, marker='o', linestyle='-', color='r', label='Trend')
    # ax2.set_ylabel('Flow Diff')  # 我们假设这是趋势线的数据
    # ax2.legend(loc='upper right')

    # 显示图表
    plt.show()



def show_data1(data):
    # 提取数据
    keys = list(data.keys())
    up_rate = [d['mean'] for d in data.values() if 'mean' in d]

    # 创建图形和坐标轴
    fig, ax = plt.subplots()
    # 绘制柱状图
    bar_width = 0.35
    indices = np.arange(len(keys))

    # 第一组柱状图
    rects1 = ax.bar(indices, up_rate, bar_width, label='平均匹配率')

    def add_labels(rects):
        for rect in rects:
            height = rect.get_height()
            ax.annotate('{}'.format(height),
                        xy=(rect.get_x() + rect.get_width() / 2, height),
                        xytext=(0, 3),  # 3 points vertical offset
                        textcoords="offset points",
                        ha='center', va='bottom')

    add_labels(rects1)
    # add_labels(rects2)

    # 添加标签和标题
    ax.set_xlabel('门架')
    ax.set_ylabel('匹配率（百分比）')
    ax.set_title('门架平均匹配率')
    ax.set_xticks(indices)
    ax.set_xticklabels(keys)
    ax.legend()

    # 显示图表
    plt.show()


def show_data2(data):
    # 提取数据
    keys = list(data.keys())
    up_rate = [d['total'] for d in data.values() if 'total' in d]
    all_rate = [d['all_rate'] for d in data.values() if 'all_rate' in d]

    # 创建图形和坐标轴
    fig, ax1 = plt.subplots()
    # 绘制柱状图
    bar_width = 0.35
    indices = np.arange(len(keys))
    # 第一组柱状图
    rects1 = ax1.bar(indices, up_rate, bar_width, label='日总流量', color='skyblue')
    # 创建第二个 Y 轴
    ax2 = ax1.twinx()
    # 第三组柱状图
    rects3 = ax2.bar(indices + bar_width, all_rate, bar_width, label='总体匹配率', color='salmon')

    # # 设置 x 轴的刻度和标签，每隔12个显示一次
    # ticks = indices[::12]  # 每隔12个索引选取一个
    # tick_labels = keys[::12]  # 对应的标签也每隔12个选取一个

    def add_labels(rects, axx):
        for rect in rects:
            height = rect.get_height()
            axx.annotate('{}'.format(height),
                        xy=(rect.get_x() + rect.get_width() / 2, height),
                        xytext=(0, 3),  # 3 points vertical offset
                        textcoords="offset points",
                        ha='center', va='bottom')

    add_labels(rects1, ax1)
    add_labels(rects3, ax2)

    ax2.set_ylabel('日总流量')  # 我们假设这是趋势线的数据
    # 设置图表的标题和标签
    ax1.set_xlabel('事件简称')
    ax1.set_ylabel('日总流量', color='b')
    ax2.set_ylabel('匹配率（百分比）', color='g')
    ax1.set_title('事件的日总流量及其匹配率')
    ax1.set_xticks(indices + bar_width / 2)  # 设置 x 轴刻度的位置
    ax1.set_xticklabels(keys)
    # 添加图例
    ax1.legend(loc='upper left')
    ax2.legend(loc='upper right')

    # 显示图表
    plt.show()


def get_data(path):
    df_up = pd.read_csv(path)
    data0 = df_up.to_dict(orient='records')
    print(data0)
    data = {}
    a = 0
    b = 0
    c = 0
    for i in range(len(data0)):
        ALL = data0[i]['Date']
        up_ = ALL.split(',')[0]
        down_ = ALL.split(',')[1].split('-')[0]
        time = ALL.split(',')[1].split('-')[1]
        area = data0[i]['area']
        if area == 'A':
            name = 'A' + str(a)
            a += 1
            data[name] = {
                "up": up_,
                "down": down_,
                "time": time,
                "up_rate": data0[i]['up'],
                "down_rate": data0[i]['down'],
                "all_rate": data0[i]['all'],
                "total": data0[i]['total']
            }
        elif area == 'B':
            name = 'B' + str(b)
            b += 1
            data[name] = {
                "up": up_,
                "down": down_,
                "time": time,
                "up_rate": data0[i]['up'],
                "down_rate": data0[i]['down'],
                "all_rate": data0[i]['all'],
                "total": data0[i]['total']
            }
        else:
            name = 'C' + str(c)
            c +=1

        # data[name] = {
        #     "up": up_,
        #     "down": down_,
        #     "time": time,
        #     "up_rate": data0[i]['up'],
        #     "down_rate": data0[i]['down'],
        #     "all_rate": data0[i]['all'],
        #     "total": data0[i]['total']
        # }
    print(data)

    return data


def get_data5(dict_data):
    menjia = {}
    name = list(dict_data.keys())
    for i in range(len(name)):
        if dict_data[name[i]]["up"] not in menjia:
            menjia[dict_data[name[i]]["up"]] = {}
            menjia[dict_data[name[i]]["up"]]["list"] = []
        menjia[dict_data[name[i]]["up"]]["list"].append(dict_data[name[i]]['up_rate'])
        if dict_data[name[i]]["down"] not in menjia:
            menjia[dict_data[name[i]]["down"]] = {}
            menjia[dict_data[name[i]]["down"]]["list"] = []
        menjia[dict_data[name[i]]["down"]]["list"].append(dict_data[name[i]]['down_rate'])

    name1 = list(menjia.keys())
    for i in range(len(name1)):
        mean_value = np.mean(menjia[name1[i]]["list"])
        rounded_mean = round(mean_value, 2)
        menjia[name1[i]]["mean"] = rounded_mean

    print(menjia)
    return menjia


def get_data2(dict_data):
    all_dict = {}
    name = list(dict_data.keys())
    for i in range(len(name)):
        all_dict[name[i]] = {}
        all_dict[name[i]]["total"] = dict_data[name[i]]["total"]
        all_dict[name[i]]["all_rate"] = dict_data[name[i]]["all_rate"]


    print(all_dict)
    return all_dict


if __name__ == '__main__':

    path = r'D:\GJ\项目\事故检测\output\all_rate.csv'

    dict_data = get_data(path)
    # name = list(dict_data.keys())
    # for i in range(len(name)):
    #     print(name[i], " ", dict_data[name[i]]["up"], " ", dict_data[name[i]]["down"], " ", dict_data[name[i]]["time"])
    # show(dict_data)

    # menjia = get_data5(dict_data)
    # show_data1(menjia)

    all_dict = get_data2(dict_data)
    show_data2(all_dict)






